//
//  PlacesModel.m
//  places
//
//  Created by adamgliea on 11-6-8.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PlacesModel.h"
#import "PlacesItem.h"

#define PLACES_COUNT 100
#define URL_STRING_TEMPLATE @"http://api.flickr.com/services/rest/\
?method=flickr.places.getTopPlacesList&\
api_key=7c4aba3ec3363e83f00ca1c5baac974e&\
place_type_id=%u&format=rest"

@interface PlacesModel()

+ (NSInteger) getTypeIdWithString:(NSString *)typeString;

- (NSData *) getPlacesWithHttp:(NSString *)typeString;
- (BOOL) parseHttpRet:(NSData *)ret;

@end


@implementation PlacesModel

@synthesize typeArray;
@synthesize curPlaceTypeIndex;
@synthesize curPlaceList;

// private functions

+ (NSInteger) getTypeIdWithString:(NSString *)typeString
{
    NSInteger ret = -1;

    if ([typeString isEqualToString:@"neighbourhood"])
        ret = 22;
    else if ([typeString isEqualToString:@"locality"])
        ret = 7;
    else if ([typeString isEqualToString:@"region"])
        ret = 8;
    else if ([typeString isEqualToString:@"country"])
        ret = 12;
    else if ([typeString isEqualToString:@"continent"])
        ret = 29;

    return ret;
}

- (NSData *) getPlacesWithHttp:(NSString *)typeString
{
    NSString *urlString = [NSString stringWithFormat:URL_STRING_TEMPLATE, [PlacesModel getTypeIdWithString:typeString]];
    NSString *encodeUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *requestURL = [NSURL URLWithString:encodeUrlString];
    NSURLResponse *response = [[NSURLResponse alloc] init];
    NSError *urlError = [[NSError alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];

    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&urlError];

    [response release];
    [urlError release];
    
    return retData != nil ? retData : nil;
}

- (BOOL) parseHttpRet:(NSData *)ret
{
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:ret];

    if (xmlParser == nil) {
        NSLog(@"parse error");
        [xmlParser release];
        return NO;
    }

    [curPlaceList removeAllObjects];
    
    [xmlParser setDelegate:self];
    return [xmlParser parse];
}

// NSXMLParserDelegate functions

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 
         qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"rsp"]){
        NSString *rspStat = [attributeDict objectForKey:@"stat"];
        if (![rspStat isEqualToString:@"ok"]) {
            [parser abortParsing];
        }
        
        return;
    }
    
    if ([elementName isEqualToString:@"place"]){
        PlacesItem *item = [[PlacesItem alloc] initWithPlaceID:[attributeDict objectForKey:@"place_id"]];
        [curPlaceList addObject:item];
        [item release];
    }
}

// public functions

- (id) init
{
    self = [super init];
    if (self != nil) {
        if (typeArray == nil) {
            typeArray = [[NSArray arrayWithObjects:
                         @"neighbourhood", @"locality", @"region", @"country", @"continent", 
                         nil] retain];
        }
    
        if (curPlaceList == nil)
            curPlaceList = [[NSMutableArray arrayWithCapacity:PLACES_COUNT] retain];
    }
    
    return self;
}

- (BOOL) loadPlacesFromFlickrWithType:(NSString *)typeString
{
    NSData *httpRet = [self getPlacesWithHttp:typeString];
    if (httpRet == nil) {
        NSLog(@"get places fail!");
        return NO;
    }

    return [self parseHttpRet:httpRet];
}

- (void) dealloc
{
    [curPlaceList release];
    [typeArray release];
    [super dealloc];
}

@end
